<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow;
          header_list[e].value = header_list[e].type == 'input_number' ? ['', ''] : '';
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : '';
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>公司账单</div>
        <div class="flex">
          <el-button type="primary" @click="(add_form_data.id = ''), (show_box = true);"
            >奖/罚</el-button
          >
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable;
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true;
                });
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e;
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height: height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column
          label="项目名称"
          prop="projectName"
          key="项目名称"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="类型"
          prop="taskName"
          key="类型"
          sortable
          v-if="header_list[1].showTable"
        >
          <template #default="scope">
            <div v-for="item in type_list" :key="item.id">
              <span v-if="scope.row.type == item.dictCode">{{ item.dictValue }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="面积"
          prop="area"
          key="面积"
          sortable
          v-if="header_list[2].showTable"
        ></el-table-column>
        <el-table-column
          label="单价"
          prop="price"
          key="单价"
          sortable
          v-if="header_list[3].showTable"
        ></el-table-column>
        <el-table-column
          label="占比"
          prop="rate"
          key="占比"
          sortable
          v-if="header_list[4].showTable"
        ></el-table-column>
        <el-table-column
          label="金额"
          prop="amount"
          key="金额"
          sortable
          v-if="header_list[5].showTable"
        ></el-table-column>
        <el-table-column
          label="已核销金额"
          prop="verificationAmount"
          key="已核销金额"
          sortable
          v-if="header_list[6].showTable"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          key="创建时间"
          sortable
          v-if="header_list[7].showTable"
          ><template #default="scope">
            <div v-if="scope.row.createTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.createTime), "YYYY-MM-DD") }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        >
        <el-table-column
          label="创建人"
          prop="createByName"
          key="创建人"
          sortable
          v-if="header_list[8].showTable"
        ></el-table-column>
        <el-table-column
          label="原因"
          prop="reason"
          key="原因"
          sortable
          show-overflow-tooltip
          v-if="header_list[9].showTable"
        ></el-table-column>
        <el-table-column
          label="核销状态"
          key="核销状态"
          sortable
          prop="isDelete"
          v-if="header_list[10].showTable"
        >
          <template #default="scope">
            <div v-if="scope.row.verificationTime === null">未核销</div>
            <div v-else>已核销</div>
          </template></el-table-column
        >
        <el-table-column
          label="核销时间"
          prop="verificationTime"
          key="核销时间"
          sortable
          v-if="header_list[11].showTable"
          ><template #default="scope">
            <div v-if="scope.row.verificationTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.verificationTime), "YYYY-MM-DD") }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        >

        <el-table-column label="操作" width="240">
          <template #default="scope: any">
            <el-button
              @click="edit_list({ item: scope.row, type: 1 })"
              v-if="
                scope.row.verificationTime == null &&
                scope.row.verificationAmount === null
              "
              >编辑</el-button
            >
            <el-button
              @click="edit_list({ item: scope.row, type: 2 })"
              v-if="scope.row.verificationTime == null"
              >核销</el-button
            ><el-button @click="edit_list({ item: scope.row, type: 3 })"
              >核销详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="30%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="resetForm(addRewardform)"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增</h4>
        <h4 v-if="add_form_data.id != '' && [1, 3].includes(edit_type)">编辑</h4>
        <h4 v-if="edit_type == 2">核销</h4>
      </template>
      <template #default>
        <el-form
          ref="addRewardform"
          :model="add_form_data"
          :rules="rules"
          label-width="120"
        >
          <el-form-item label="项目" prop="taskId">
            <el-select
              v-model="add_form_data.taskId"
              :disabled="
                [2, 3].includes(edit_type) ||
                (edit_type == 1 && [1, 2].includes(add_form_data.type))
              "
            >
              <el-option
                v-for="item in add_form_data.type == 1 || edit_type == 3
                  ? project_list
                  : project_list.filter((i) => {
                      return i.planHours == 1;
                    })"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="add_form_data.type"
              :disabled="
                [2, 3].includes(edit_type) ||
                (edit_type == 1 && [1, 2].includes(add_form_data.type))
              "
            >
              <el-option
                v-if="
                  [2, 3].includes(edit_type) ||
                  (edit_type == 1 && [1, 2].includes(add_form_data.type))
                "
                :value="1"
                label="预付款"
              ></el-option>
              <el-option
                v-if="
                  [2, 3].includes(edit_type) ||
                  (edit_type == 1 && [1, 2].includes(add_form_data.type))
                "
                :value="2"
                label="尾款"
              ></el-option>
              <el-option :value="3" label="奖励"></el-option>
              <el-option :value="4" label="处罚"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input type="number" style="width: 200px" v-model="add_form_data.amount">
            </el-input>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
              :clearable="false"
              v-model="add_form_data.occurrenceTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="原因" v-if="edit_type == 1">
            <el-input
              v-model="add_form_data.reason"
              type="textarea"
              show-word-limit
              maxlength="300"
            >
            </el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="show_box = false">取消</el-button>
            <el-button
              type="primary"
              @click="submit(addRewardform)"
              :loading="btn_loading"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
    <el-drawer
      v-model="show_list_box"
      direction="rtl"
      size="50%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="(edit_type = 1), (add_form_data.type = 3);"
    >
      <template #title>
        <h4>核销记录</h4>
      </template>
      <template #default>
        <el-table :data="box_list" border class="tc" max-height="600">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="项目名称" prop="projectName"></el-table-column>
          <el-table-column label="类型" prop="taskName">
            <template #default="scope">
              <div v-for="item in type_list" :key="item.id">
                <span v-if="scope.row.type == item.dictCode">{{ item.dictValue }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount"></el-table-column>
          <el-table-column label="时间"
            ><template #default="scope">
              <div v-if="scope.row.time ?? '' !== ''">
                {{ formatDate(parseInt(scope.row.time), "YYYY-MM-DD") }}
              </div>
              <div v-else>-- --</div>
            </template></el-table-column
          >
          <el-table-column label="操作" width="160" v-if="!verificationStatus">
            <template #default="scope: any">
              <el-button @click="edit_box_list({ item: scope.row, type: 3 })"
                >编辑</el-button
              >
              <el-button @click="edit_box_list({ item: scope.row, type: 4 })"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import {
  check_role,
  formatDate,
  debounce,
  handle_search_key,
  dictData,
} from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import { onMounted, ref, computed, onUnmounted } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { FormInstance, ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
const store = useStore();
const addRewardform = ref<FormInstance>();
const customize = (rule: any, value: any, callback: any) => {
  // 角色代号表单校验
  if (!value) {
    return callback(new Error("请输入金额"));
  }
  if (value <= 0) {
    return callback(new Error("金额需大于0"));
  }
  callback();
};
const rules = ref({
  // 表单验证规则
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  taskId: [{ required: true, message: "请选择项目", trigger: "change" }],
  memberId: [{ required: true, message: "请选择成员", trigger: "change" }],
  proportion: [{ required: true, message: "请输入比例", trigger: "blur" }],
  amount: [{ required: true, validator: customize, trigger: "blur" }],
});
const list = ref();
const total = ref();
const max_height = ref();
const loading = ref(false);
const show_box = ref(false);
const show_list_box = ref(false);
const height_size = ref(1);
const header_list = ref<any>([
  {
    label: "项目名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "类型",
    value: "",
    showTable: true,
    type: "select",
    isShow: true,
    options: computed(() => {
      return type_list.value;
    }),
  },
  {
    label: "面积",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "单价",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "占比",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "金额",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "已核销金额",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "创建时间",
    value: "",
    showTable: true,
    type: "date",
    isShow: false,
    options: [],
  },
  {
    label: "创建人",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "原因",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "核销状态",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        value: true,
        label: "已核销",
      },
      {
        value: false,
        label: "未核销",
      },
    ],
  },
  {
    label: "核销时间",
    value: "",
    showTable: true,
    type: "date",
    isShow: false,
    options: [],
  },
]);
const page_data = ref({
  current: 1,
  pageSize: 10,
  enterpriseId: store.state.enterprise_id,
  projectName: "",
  type: "",
  area: "",
  price: "",
  rate: "",
  amount: "",
  verificationAmount: "",
  createTime: "",
  createByName: "",
  reason: "",
  verificationStatus: "",
  verificationTime: "",
});
const add_form_data = ref({
  id: "",
  taskId: "",
  type: 3,
  amount: "",
  occurrenceTime: Date.parse(new Date() + ""),
  reason: "",
  projectName: "",
});
const maxAmount = ref<number>();
const verificationAmount = ref("");
const type_list = ref([]);
onMounted(() => {
  max_height.value = window.innerHeight - 320; // 带分页的 table 高度
  EventBus.on("refresh", () => {
    get_list();
    ElMessage.success("刷新成功！");
  });
  setTimeout(() => {
    get_list();
    dictData("1711199498639773697").then((res) => {
      type_list.value = res as any;
      type_list.value.forEach((item) => {
        item.label = item.dictValue;
        item.value = item.dictCode;
      });
    }); // 字典中 账单类型 对应的值
    get_myProjectTaskList();
  }, 100);
});
const project_list = ref([]); // 项目列表
const get_myProjectTaskList = () => {
  axios
    .request({
      url: serviceApi.tesk_list,
      method: "post",
      data: { current: 1, pageSize: 1000 },
    })
    .then((res) => {
      console.log(res);
      project_list.value = res.data.content;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
onUnmounted(() => {
  EventBus.off("refresh");
});
const edit_box_list = (e) => {
  console.log(e);
  if (e.type == 4) {
    ElMessageBox.confirm("确定删除该记录？", "", {
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      closeOnClickModal: false,
      type: "warning",
    }).then(() => {
      axios
        .request({
          url: serviceApi.enterpriseBill + "/deleteEnterpriseBillLog/" + e.item.id,
          method: "delete",
        })
        .then(() => {
          ElMessage.success("操作成功！");
          box_list.value = box_list.value.filter((i) => {
            return i.id != e.item.id;
          });
          setTimeout(() => {
            get_list();
          }, 1000);
        })
        .catch((err) => {
          ElMessage.error(err);
        })
        .catch(() => {});
    });
  } else {
    console.log(maxAmount.value);
    edit_type.value = e.type;
    add_form_data.value = {
      id: e.item.id,
      taskId: e.item.taskId,
      type: e.item.type,
      amount: e.item.amount,
      occurrenceTime: !e.item.time ? Date.parse(new Date() + "") : Number(e.item.time),
      reason: e.item.reason,
      projectName: e.item.projectName,
    };
    maxAmount.value += Number(e.item.amount);
    show_box.value = true;
  }
};
const edit_type = ref<number>(1);
const verificationStatus = ref(false);
const taskId = ref("");
const list_id = ref("");
const edit_list = (e) => {
  console.log(e);
  edit_type.value = e.type;
  verificationAmount.value = e.item.verificationAmount ?? "";
  maxAmount.value = e.item.amount - (e.item.verificationAmount ?? "");
  add_form_data.value.id = e.item.id;
  add_form_data.value.projectName = e.item.projectName;
  add_form_data.value.type = e.item.type;
  taskId.value = e.item.taskId;
  list_id.value = e.item.id;
  if ([1, 2].includes(e.type)) {
    add_form_data.value = {
      id: e.item.id,
      projectName: e.item.projectName,
      taskId: e.item.taskId,
      type: e.item.type,
      amount: (e.item.amount - e.item.verificationAmount) as any,
      occurrenceTime:
        e.type == 2 ? Date.parse(new Date() + "") : Number(e.item.occurrenceTime),
      reason: e.item.reason,
    };
    show_box.value = true;
  } else {
    verificationStatus.value = e.item.verificationTime !== null;
    get_box_list();
  }
};
const box_list = ref([]);
const get_box_list = () => {
  console.log(add_form_data.value.id);
  axios
    .request({
      url: serviceApi.enterpriseBill + "/getEnterpriseBillLogList",
      method: "post",
      params: { enterpriseBillId: list_id.value },
    })
    .then((res) => {
      console.log(res);
      res.data.forEach((i) => {
        i.projectName = add_form_data.value.projectName;
        i.type = add_form_data.value.type;
        i.taskId = taskId.value;
      });
      box_list.value = res.data.filter((i) => {
        return i.isDelete == false;
      });
      console.log(box_list.value);
      show_list_box.value = true;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const btn_loading = ref(false);
// 奖罚 新增  编辑 核销
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if ([2, 3].includes(edit_type.value)) {
        if (Number(add_form_data.value.amount) > maxAmount.value) {
          add_form_data.value.amount = "";
          ElMessage.error("金额不得超过最大可核销金额");
          return;
        }
      }
      if (add_form_data.value.id != "" && edit_type.value == 2) {
        if (verificationAmount.value != "") {
          submit_request();
        } else {
          ElMessageBox.confirm("记录核销后将不可在编辑", "", {
            cancelButtonText: "取消",
            confirmButtonText: "确定",
            closeOnClickModal: false,
            type: "warning",
          })
            .then(() => {
              submit_request();
            })
            .catch(() => {});
        }
      } else {
        submit_request();
      }
    }
  });
};
// 奖励 惩罚 核销 编辑核销
const submit_request = () => {
  if (btn_loading.value) return;
  btn_loading.value = true;
  add_form_data.value = Object.assign(add_form_data.value, {
    time: add_form_data.value.occurrenceTime,
  });
  axios
    .request({
      url:
        serviceApi.enterpriseBill +
        (add_form_data.value.id == ""
          ? "/rewardsOrFines"
          : edit_type.value == 1
          ? "/rewardsOrFines/" + add_form_data.value.id
          : edit_type.value == 2
          ? "/verification/" + add_form_data.value.id
          : "/editEnterpriseBillLog/" + add_form_data.value.id),
      method: add_form_data.value.id == "" ? "post" : "put",
      data: add_form_data.value,
    })
    .then((res) => {
      console.log(res);
      ElMessage.success("操作成功！");
      setTimeout(() => {
        btn_loading.value = false;
        show_list_box.value ? get_box_list() : "";
        get_list();
        resetForm(addRewardform.value);
      }, 1000);
    })
    .catch((err) => {
      btn_loading.value = false;
      ElMessage.error(err);
    });
};
const get_list = () => {
  loading.value = true;
  axios
    .request({
      url: serviceApi.enterpriseBill + "/page",
      method: "post",
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res);
      list.value = res.data.content;
      total.value = parseInt(res.data.totalElements);
      let item = list.value.filter((i) => {
        return i.id == list_id.value;
      });
      if (item.length) {
        verificationStatus.value = item[0].verificationTime !== null;
      }
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
      loading.value = false;
    });
};
let list_debounce = debounce(200, get_list);
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    enterpriseId: store.state.enterprise_id,
    projectName: header_list.value[0].value,
    type: header_list.value[1].value,
    area: header_list.value[2].value,
    price: header_list.value[3].value,
    rate: header_list.value[4].value,
    amount: header_list.value[5].value,
    verificationAmount: header_list.value[6].value,
    createTime: header_list.value[7].value,
    createByName: header_list.value[8].value,
    reason: header_list.value[9].value,
    verificationStatus:
      header_list.value[10].value == undefined ? false : header_list.value[10].value,
    verificationTime: header_list.value[11].value,
  };
  get_list();
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  console.log(maxAmount.value);
  verificationAmount.value = show_list_box.value ? verificationAmount.value : "";
  maxAmount.value = show_list_box.value
    ? maxAmount.value - Number(add_form_data.value.amount)
    : 0;
  add_form_data.value = {
    projectName: add_form_data.value.projectName,
    id: "",
    taskId: "",
    type: show_list_box.value ? add_form_data.value.type : 3,
    amount: "",
    occurrenceTime: Date.parse(new Date() + ""),
    reason: "",
  };
  console.log(add_form_data.value);
  show_box.value = false;
  edit_type.value = 1;
};
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
